package com.cms.filter;

import com.cms.constant.CommonConstant;
import com.cms.domain.Config;
import com.cms.entity.*;
import com.cms.enums.SiteType;
import com.cms.service.*;
import com.cms.utils.CommonUtils;
import com.cms.utils.SystemUtils;
import com.cms.utils.WebUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Component
public class UrlFilter implements Filter {


    @Autowired
    private TagService tagService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SiteService siteService;

    @Autowired
    private WebService webService;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private NavService navService;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        String url = request.getRequestURI();
        String contextPath = request.getContextPath();
        url = url.substring(contextPath.length());
        //查询当前站点
        String domain = WebUtils.getDomain();
        String[] urls = url.split("/");
        Long siteNum = siteService.selectCount(domain);
        Site currentSite = null;
        if((siteNum==null || siteNum<1) && urls.length>1){//无域名带URL目录
            String cat = urls[1];
            if(!CommonUtils.urlExcludes.contains("/"+cat)){
                currentSite = siteService.findByType(SiteType.CAT,cat,null);
                if(currentSite != null){
                    url = url.substring(("/"+cat).length());
                }
            }
        }else{//有域名
            currentSite = siteService.findByType(SiteType.DOMAIN,null,domain);
        }
        if(currentSite==null){
            currentSite = siteService.findDefault();
        }
        request.setAttribute(CommonConstant.CURRENT_SITE, currentSite);
        Web currentWeb = webService.findBySiteId(currentSite.getId());
        request.setAttribute(CommonConstant.CURRENT_WEB, currentWeb);
        Company currentCompany = companyService.findBySiteId(currentSite.getId());
        request.setAttribute(CommonConstant.CURRENT_COMPANY, currentCompany);
        request.setAttribute(CommonConstant.TPATH,contextPath+"/templates/"+currentSite.getPcTemplate());
        //获取后缀
        String extension = FilenameUtils.getExtension(url);
        Config config = SystemUtils.getConfig();
        //过滤地址
        if (((StringUtils.isBlank(url) || "/".equals(url)) && (config.getSiteModel()!=Config.SiteModel.HTML.ordinal())) || (StringUtils.isNotBlank(extension) && !StringUtils.equals("html",extension))
                || CommonUtils.getUrlPathContains(url)
        ) {
            UrlRewriteWrappedRequest urlRewriteWrappedRequest = new UrlRewriteWrappedRequest(request,new HashMap());
            request.getRequestDispatcher(url).forward(urlRewriteWrappedRequest,response);
            return;
        }
        //模式
        if(config.getSiteModel()== Config.SiteModel.REWRITE.ordinal()){
            url = url.replace(".html","");
        }else if(config.getSiteModel()==Config.SiteModel.HTML.ordinal()){
            if("/".equals(url) || "".equals(url)){
                url = "/index.html";
            }
            if(url.endsWith(".html")){
                UrlRewriteWrappedRequest urlRewriteWrappedRequest = new UrlRewriteWrappedRequest(request,new HashMap());
                request.getRequestDispatcher(url).forward(urlRewriteWrappedRequest,response);
                return;
            }
        }
        //参数
        HashMap overridenParameters = new HashMap();
        //tag start
        if(url.startsWith("/tag/")){
            String tagCat = url.split("/")[2];
            Tag tag = tagService.findByCat(tagCat);
            String newUrl = "";
            if(tag!=null){
                newUrl = "/tag";
                overridenParameters.put("id", new String[]{tag.getId()+""});
            }
            if(StringUtils.isNotBlank(newUrl)){
                url = newUrl;
            }
            UrlRewriteWrappedRequest urlRewriteWrappedRequest = new UrlRewriteWrappedRequest(request,overridenParameters);
            request.getRequestDispatcher(url).forward(urlRewriteWrappedRequest,response);
            return;
        }
        //tag end
        //URL目录: /product  /product/{id}
        String target = url;
        String[] targets = url.split("/");
        //设置导航
        String navTarget = "/"+targets[1];
        Nav currentNav = navService.findByUrl(navTarget,currentSite.getId());
        request.setAttribute(CommonConstant.CURRENT_NAV, currentNav);
        //设置栏目和内容
        int targetsLength = targets.length;
        if(targetsLength==2){
            String categoryCat = targets[1];
            Category category = categoryService.findByCat(categoryCat,currentSite.getId());
            if(category!=null){
                target = "/category";
                overridenParameters.put("id", new String[]{category.getId()+""});
            }
        }else if(targetsLength==3){
            String categoryCat = targets[1];
            String contentId = targets[2];
            Category category = categoryService.findByCat(categoryCat,currentSite.getId());
            if(category!=null){
                target = "/content";
                overridenParameters.put("id", new String[]{contentId+""});
            }
        }
        UrlRewriteWrappedRequest urlRewriteWrappedRequest = new UrlRewriteWrappedRequest(request,overridenParameters);
        request.getRequestDispatcher(target).forward(urlRewriteWrappedRequest,response);
    }

    @Override
    public void destroy() {

    }
}
